'use strict'

/**
 * Created by chenyuqi on 2017/7/8.
 */

var path = require('path');
 
var config = require('../config');
var Wechat = require('../wechat/wechat');

var wechatApi = new Wechat(config.wechat);


/*
var menu = require('./menu');
wechatApi.deleteMenu()
	.then(function(){
		return wechatApi.createMenu(menu);
	})
	.then(function(data){
		console.log(data);
	});
*/


exports.reply = function* (next){
    // g.js 内的 this.weixin
    var message = this.weixin;

    // 事件处理
    if (message.MsgType === 'event') {
        if (message.Event === 'subscribe') {
            if (message.EventKey) {
				// ticket 可以换取二维码图片
                console.log('扫二维码进来：' + message.EventKey + ' ' + message.Ticket);
            }
            this.body = '哈哈，你订阅了这个公众号\r\n';// + ' 消息ID：' + message.MsgId;
        } else if (message.Event === 'unsubscribe') {
            console.log('无情取关');
			this.body = '';
        } else if (message.Event === 'LOCATION') {
            // console.log('无情取关');
			this.body = '您上报的位置是：' + message.Latitude + '/' + message.Longitude
				+ '-' + message.Precision;
        } else if (message.Event === 'CLICK') {
            // console.log('无情取关');
			this.body = '您点击了菜单：' + message.EventKey;
        } else if (message.Event === 'SCAN') {
            console.log('关注后扫二维码' + message.EventKey + ' ' + message.Ticket);
			this.body = '看到您扫了一下哦';
        } else if (message.Event === 'VIEW') {
            // console.log('无情取关');
			// 此类事件中，message.EventKey 就是 url 地址
			this.body = '您点击了菜单中的链接：' + message.EventKey;
        } else if (message.Event === 'scancode_push') {
            console.log(message.ScanCodeInfo.ScanType);
			console.log(message.ScanCodeInfo.ScanResult);
			this.body = '扫码推送：' + message.EventKey;
        } else if (message.Event === 'scancode_waitmsg') {
			console.log(message.ScanCodeInfo.ScanType);
			console.log(message.ScanCodeInfo.ScanResult);
			this.body = '扫码推送等待：' + message.EventKey;
        } else if (message.Event === 'pic_sysphoto') {
			console.log(message.SendPicsInfo.PicList);
			console.log(message.SendPicsInfo.Count);
			this.body = '系统拍照：' + message.EventKey;
        } else if (message.Event === 'pic_photo_or_album') {
			console.log(message.SendPicsInfo.PicList);
			console.log(message.SendPicsInfo.Count);
			this.body = '弹出拍照或相册：' + message.EventKey;
        } else if (message.Event === 'pic_weixin') {
			console.log(message.SendPicsInfo.PicList);
			console.log(message.SendPicsInfo.Count);
			this.body = '微信相册发图：' + message.EventKey;
        } else if (message.Event === 'location_select') {
			console.log(message.SendLocationInfo.Location_X);
			console.log(message.SendLocationInfo.Location_Y);
			console.log(message.SendLocationInfo.Scale);
			console.log(message.SendLocationInfo.Label);
			console.log(message.SendLocationInfo.Poiname);
			this.body = '地理位置选择：' + message.EventKey;
        }
    } else if (message.MsgType === 'text') {
		var content = message.Content;
		var reply = '您说的 ' + content + ' 太复杂了';
		if (content == 1) {
			reply = '天下第一吃大米';
		} else if (content == 2) {
			reply = '天下第二吃豆腐';
		} else if (content == 3) {
			reply = '天下第三吃仙丹';
		} else if (content == 4) {
			// 回复图文消息，可以尝试单个和多个，看有什么不同
			// 比如描述，多图文时没有显示，单图文时有显示，还有时间和阅读全文。
			reply = [{
				title: '技术改变世界',
				description: '技术改变世界的描述',
				picUrl: '网络上某个图片的 url 即可 http://res.cloudinary.com/moveha/image/upload/v1441184110/assets/images/Mask-min.png',
				url: 'https://github.com'
			}, {
				title: 'Nodejs 微信开发',
				description: '爽到爆',
				picUrl: '网络上某个图片的 url 即可 http://res.cloudinary.com/moveha/image/upload/v1431337192/index-img2_fvzeow.png',
				url: 'https://nodejs.org'
			}];
		} else if (content === '5') {
			// 上传临时图片素材
			var data = yield wechatApi.uploadMaterial('image', path.join(__dirname + '/5.jpg');
			reply = {
				type: 'image',
				mediaId: data.media_id
			};
			console.log(reply);
		} else if (content === '6') {
			// 上传临时视频素材
			var data = yield wechatApi.uploadMaterial('video', path.join(__dirname + '../6.mp4'));
			reply = {
				type: 'video',
				title: '视频的标题',
				description: '视频的描述',
				mediaId: data.media_id
			};
			console.log(reply);
		} else if (content === '7') {
			// 上传临时音乐素材
			var data = yield wechatApi.uploadMaterial('music', path.join(__dirname + '../7.mp3'));
			reply = {
				type: 'music',
				title: '音乐的标题',
				description: '音乐的描述',
				musicUrl: '音乐文件url',
				thumbMediaId: data.media_id
			};
			console.log(reply);
		} else if (content === '8') {
			// 上传永久图片素材
			// 第三个参数意义在于声明上传的是一个永久素材
			var data = yield wechatApi.uploadMaterial('image', path.join(__dirname + '../5.jpg'), {type: 'image'});
			reply = {
				type: 'image',
				mediaId: data.media_id
			};
			console.log(reply);
		} else if (content === '9') {
			// 上传永久视频素材
			var data = yield wechatApi.uploadMaterial('video', path.join(__dirname + '../6.mp4'), {
				type: 'video', 
				description: '{"title":"json字符串中的title", "introduction":"json字符串中的introduction"}'
			});
			reply = {
				type: 'video',
				title: '视频的标题',
				description: '视频的描述',
				mediaId: data.media_id
			};
			console.log(reply);
		} else if (content === '10') {
			// 上传图片，获取图片id，
			// 使用图片id上传图文素材
			// 获取图文素材
			// 把图文素材回复给用户
			
			// 上传图文素材需要的图片素材
			var picData = yield wechatApi.uploadMaterial('image', path.join(__dirname + '../5.jpg'), {});
			
			var media = {
				articles: [{
					title: '上传的图文素材的标题111',
					thumb_media_id: picData.media_id,
					author: 'Sccot',
					digest: '摘要摘要',
					show_cover_pic: 1,
					content: 'hello world',
					content_source_url: 'https://github.com'
				}]
			};
			
			data = yield wechatApi.uploadMaterial('news', media, {});
			data = yield wechatApi.fetchMaterial(data.media_id, 'news', {});
			console.log(data);
			
			var items = data.news_item;
			var news = [];
			items.forEach(function(item){
				news.push({
					title: item.title,
					description: item.digest,
					picUrl: picData.url,
					url: item.url
				});
			});
			
			reply = news;
		} else if (content === '11') {
			// 获取素材数量
			var countsObj = yield wechatApi.countMaterial();
			console.log(JSON.stringify(countsObj));
			
			// 获取素材列表
			/*var list1 = yield wechatApi.batchMaterial({
				offset: 0,
				count: 10,
				type: 'image'
			});
			var list2 = yield wechatApi.batchMaterial({
				offset: 0,
				count: 10,
				type: 'video'
			});
			var list3 = yield wechatApi.batchMaterial({
				offset: 0,
				count: 10,
				type: 'voice'
			});
			var list4 = yield wechatApi.batchMaterial({
				offset: 0,
				count: 10,
				type: 'news'
			});*/
			// 高级的功能，可以实现并发运行
			var results = yield [
				wechatApi.batchMaterial({
					offset: 0,
					count: 10,
					type: 'image'
				}),
				wechatApi.batchMaterial({
					offset: 0,
					count: 10,
					type: 'video'
				}),
				wechatApi.batchMaterial({
					offset: 0,
					count: 10,
					type: 'voice'
				}),
				wechatApi.batchMaterial({
					offset: 0,
					count: 10,
					type: 'news'
				})
			];
			
			console.log(results);
			console.log(JSON.stringify(results));//内容会非常非常多
			reply = 'hehe';
		} else if (content === '11') {
			// 分组操作
			var group = yield wechatApi.createGroup('打卡啦');
			console.log('新分组 打卡啦');
			console.log(group);
			
			var groups = yield wechatApi.fetchGroup();
			console.log('查看所有分组');
			console.log(groups);
			
			var group2 = yield wechatApi.checkGroup(message.FromUserName);
			console.log('查看自己所在分组');
			console.log(group2);
			
			reply = 'group done';
		}
		
		this.body = reply;
    }
    yield next;
};